//
//  CustomView.m
//  Perking
//
//  Created by tim on 16/7/7.
//  Copyright © 2016年 tim. All rights reserved.
//
/*
// 创建自定义的View
CustomView *customView = [[CustomView alloc] init];
// 设置数据
CustomModel *model = [CustomModel modelWithName:@"hosea_zhou" icon:@"1"];
customView.model = model;
// 设置frame
customView.frame = CGRectMake(100, 100, 67, 100);
// 添加子控件
[self.view addSubview:customView];
 */

#import "CustomView.h"
#import "CustomModel.h"

@interface CustomView ()
//在刚刚新建类的`类扩展`中添加子控件属性（用`weak`声明，防止内存泄露）
@property (nonatomic, weak) UIImageView *iconImageView;

@property (nonatomic, weak) UILabel *nameLabel;

@end

@implementation CustomView

// 在initWithFrame:方法中添加子控件
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 注意：该处不要给子控件设置frame与数据，可以在这里初始化子控件的属性
        UIImageView *iconImageView = [[UIImageView alloc] init];

        self.iconImageView = iconImageView;
        //平铺图片
        self.iconImageView.contentMode=UIViewContentModeScaleAspectFill;
        
        [self addSubview:iconImageView];
        
        UILabel *nameLabel = [[UILabel alloc] init];
        // 设置子控件的属性
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.font = _kFont26;

        
        nameLabel.textColor=kColor3C3C3C;
        self.nameLabel = nameLabel;
        [self addSubview:nameLabel];
    }
    return self;
}

// 在`layoutSubviews`方法中设置子控件的`frame`（在该方法中一定要调用`[super layoutSubviews]`方法）
- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat egdeH = 13;

    self.iconImageView.height = self.iconImageView.width = 40 * 1.3;
    self.iconImageView.center = CGRectGetCenter(self.bounds);
    self.iconImageView.layer.cornerRadius=3;
    self.iconImageView.layer.masksToBounds=YES;

    
    [self.nameLabel sizeToFit];
    self.nameLabel.bottom = self.height - egdeH;
    self.nameLabel.centerX = self.iconImageView.centerX;
    
    self.iconImageView.bottom = self.nameLabel.top - 10;
}

//在该`setter`方法中取出模型属性，给对应的子控件赋值
- (void)setModel:(CustomModel *)model
{
    _model = model;
    
     if ([model.icon hasPrefix:@"http://"] )
    {
       
        [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"placehoder2"]];
    }else {
        
        self.iconImageView.image = [UIImage imageNamed:model.icon];
        
    }
    
    self.nameLabel.text = model.name;
    
}



@end
